package com.jack.serialportlib;

import android.os.Handler;
import android.os.HandlerThread;
import android.serialport.SerialPort;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;


public class SerialPortMicHelper implements Constant {
    private static final String TAG = SerialPortMicHelper.class.getSimpleName();
    private static volatile SerialPortMicHelper single;
    private SerialPort serialPort;
    private OutputStream outputStream;
    private Handler writeHandler;
    private HandlerThread writeThread;

    public static SerialPortMicHelper getInstance() {
        if (null == single) {
            synchronized (SerialPortMicHelper.class) {
                if (null == single) {
                    single = new SerialPortMicHelper();
                }
            }
        }
        return single;
    }

    private SerialPortMicHelper() {

    }

    /** 打开串口*/
    public void open(String device) throws IOException {
        if (serialPort != null) {
            Log.i(TAG, "open: close");
            close();
        }
        if (TextUtils.isEmpty(device)){
            device = MIC_DEVICE_PATH;
        }
        serialPort = new SerialPort(device, MIC_DEVICE_BAUDRATE);
        outputStream = serialPort.getOutputStream();
        writeThread = new HandlerThread("write-mic-thread");
        writeThread.start();
        writeHandler = new Handler(writeThread.getLooper());
    }

    public boolean isOpen() {
        return serialPort != null;
    }

    /** 关闭串口 */
    public void close() {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (writeThread != null) {
            writeThread.quit();
        }

        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }

    public void sendHex(String sHex) {
        sHex = sHex.replace(" ", "");
        byte[] bOutArray = Tool.HexToByteArr(sHex);
        send(bOutArray);
    }

    /**
     * 发送数据
     *
     * @param datas
     * @return
     */
    public void send(final byte[] datas) {
        if (serialPort != null)
            writeHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        outputStream.write(datas);
                        outputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
    }
}
